import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2022-12-21
 * Time: 4:00
 */
//测试事务操作，以余额和支出为例子
public class Test_Transaction {
    public static void main(String[] args) throws InterruptedException {
        Jedis jedis=new Jedis("101.35.154.52",6379);
        //首先在redis服务端设置余额为100，支出为0
        int yue= Integer.parseInt(jedis.get("yue"));
        //System.out.println(yue);
        
        int zhichu=10;
        //监控余额，如果有人修改这个值，那么事务就提交不成功，修改失败，保证了安全性
        jedis.watch("yue");
        Thread.sleep(3000); //模拟网络延迟
        if(yue<zhichu){
            jedis.unwatch();
            System.out.println("余额不足！");
        }else{
            //提交事务,事务开启后不再使用jedis实例
            Transaction transaction=jedis.multi();
            //做事
            transaction.decrBy("yue",zhichu); //余额减少
            transaction.incrBy("zhichu",zhichu); //消费增加
            //提交事务
            transaction.exec();
            System.out.println("余额:"+jedis.get("yue"));
            System.out.println("累计支出:"+jedis.get("zhichu"));
            
        }
        
    }
}
